package com.xkstream.client.ui;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.nfc.Tag;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.xkstream.client.R;
import com.xkstream.client.api.API;
import com.xkstream.client.application.Application;
import com.xkstream.client.appmanager.AppManager;
import com.xkstream.client.base.BaseActivity;
import com.xkstream.client.base.BaseData;
import com.xkstream.client.base.WatcherAdapter;
import com.xkstream.client.camera.utils.FileUtils;
import com.xkstream.client.entity.AnchorInfo;
import com.xkstream.client.entity.Area;
import com.xkstream.client.entity.BetRank;
import com.xkstream.client.entity.User;
import com.xkstream.client.http.FileUploadUtil;
import com.xkstream.client.presenter.AnchorApplyContract;
import com.xkstream.client.presenter.AnchorApplyPresenter;
import com.xkstream.client.rx.Rxbus;
import com.xkstream.client.utils.BitmapUtil;
import com.xkstream.client.utils.DeviceUtils;
import com.xkstream.client.utils.LogUtil;
import com.xkstream.client.view.BottomPopupWindow;
import com.xkstream.client.view.BottomPushPopupWindow;
import com.xkstream.client.view.ResizeLayout;

import java.io.File;
import java.io.IOException;
import java.lang.ref.PhantomReference;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;
import java.util.WeakHashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by xiaoyi on 2017-9-26.
 * 主播申请
 */

public class AnchorApplyActivity extends BaseActivity<AnchorApplyContract.Presenter>
        implements AnchorApplyContract.View {
    private static final int CODE_LOCATION = 0x1000;
    private static final int CODE_CAMERA_01 = 0X2001;
    private static final int CODE_CAMERA_02 = 0X2002;
    private static final int CODE_CAMERA_03 = 0X2003;
    private static final int CODE_CAMERA_04 = 0X2004;

    private static final int CODE_PHOTO_01 = 0X3001;
    private static final int CODE_PHOTO_02 = 0X3002;
    private static final int CODE_PHOTO_03 = 0X3003;
    private static final int CODE_PHOTO_04 = 0X3004;

    private static final int CODE_CROP_01 = 0X4001;
    private static final int CODE_CROP_02 = 0X4002;
    private static final int CODE_CROP_03 = 0X4003;
    private static final int CODE_CROP_04 = 0X4004;

    private String image_01;
    private String image_02;
    private String image_03;
    private String image_00;

    private Uri savePath;

    @BindView(R.id.ivHeader)
    ImageView ivHeader;
    @BindView(R.id.et_nickname)
    EditText etNickname;
    @BindView(R.id.et_roomname)
    EditText etRoomname;
    @BindView(R.id.et_location)
    TextView etLocation;
    @BindView(R.id.invite_code)
    EditText inviteCode;
    @BindView(R.id.img_ipload1)
    ImageView imgIpload1;
    @BindView(R.id.img_ipload2)
    ImageView imgIpload2;
    @BindView(R.id.img_ipload3)
    ImageView imgIpload3;
    @BindView(R.id.tv_submit)
    TextView tvSubmit;
    @BindView(R.id.root)
    ResizeLayout root;
    @BindView(R.id.llPhoto)
    LinearLayout llPhoto;

    private String path;

    private MHandler mHandler;

    private WatcherAdapter watcher = new WatcherAdapter() {
        @Override
        public void afterTextChanged(Editable s) {
            super.afterTextChanged(s);
            setBtnState();
        }
    };

    @Override
    protected void initViews(Bundle savedInstanceState) {
        setContentView(R.layout.activity_anchor_apply);
        ButterKnife.bind(this);
        setTitle(R.string.anchor_apply);
        presenter = new AnchorApplyPresenter(this);
        initListener();
        mHandler = new MHandler(this);
    }

    private void initListener() {
        setInputListener();
        addTextWatcher();
    }

    private void addTextWatcher() {
        etNickname.addTextChangedListener(watcher);
        etRoomname.addTextChangedListener(watcher);
    }

    private void setBtnState() {
        if (etNickname.getText().length() >= 4
                && etRoomname.getText().length() >= 2
                && etLocation.getText().length() >= 1) {
            tvSubmit.setBackgroundResource(R.drawable.btn_clickable);
        } else {
            tvSubmit.setBackgroundResource(R.drawable.btn_unclickable);
        }
    }

    private void setInputListener() {
        root.setOnKeyboardShowListener(new ResizeLayout.OnkeyboardShowListener() {
            @Override
            public void onKeyboardShow(int height) {
                int[] location = new int[2];
                llPhoto.getLocationOnScreen(location);
                int position = DeviceUtils.deviceHeight(AnchorApplyActivity.this) - location[1] - llPhoto.getHeight() / 2;
                root.setPadding(0, -(height - position), 0, 0);
            }

            @Override
            public void onKeyboardHide() {
                root.setPadding(0, 0, 0, 0);
            }
        });
    }

    @OnClick({R.id.ivHeader, R.id.et_location, R.id.img_ipload1, R.id.img_ipload2,
            R.id.img_ipload3, R.id.tv_submit, R.id.ivClose})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ivHeader:
                showPhotoSelectedDialog(0);
                break;
            case R.id.et_location:
                Intent intent = new Intent();
                intent.setClass(this, AreaCodeActivity.class);
                startActivityForResult(intent, CODE_LOCATION);
                break;
            case R.id.img_ipload1:
                showPhotoSelectedDialog(1);
                break;
            case R.id.img_ipload2:
                showPhotoSelectedDialog(2);
                break;
            case R.id.img_ipload3:
                showPhotoSelectedDialog(3);
                break;
            case R.id.tv_submit:
                submitApply();
                break;
            case R.id.ivClose:
                finish();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != -1) return;
        switch (requestCode) {
            case CODE_LOCATION:
                Area area = (Area) data.getSerializableExtra("area");
                etLocation.setText(area.getChain_name());
                setBtnState();
                break;
            case CODE_CAMERA_01:
            case CODE_CAMERA_02:
            case CODE_CAMERA_03:
            case CODE_CAMERA_04:
                startPhotoZoom(data, getCode(requestCode));
                break;
            case CODE_CROP_01:
                getBitmapFromResult(data, imgIpload1);
                break;
            case CODE_CROP_02:
                getBitmapFromResult(data, imgIpload2);
                break;
            case CODE_CROP_03:
                getBitmapFromResult(data, imgIpload3);
                break;
            case CODE_CROP_04:
                getBitmapFromResult(data, ivHeader);
                break;
            case CODE_PHOTO_01:
            case CODE_PHOTO_02:
            case CODE_PHOTO_03:
            case CODE_PHOTO_04:
                cropImage(data.getData(), getCode(requestCode));
//                getBitmapFromResult(data, ivHeader);
                break;


        }
    }

    private void cropImage(Uri imageUri, int code) {
        Intent intent = new Intent("com.android.camera.action.CROP"); // 剪裁
        intent.setDataAndType(imageUri, "image/*");
        intent.putExtra("scale", true);
        // 设置宽高比例
        intent.putExtra("aspectX", 400);
        intent.putExtra("aspectY", 400);
        // 设置裁剪图片宽高
        intent.putExtra("outputX", DeviceUtils.dp2px(this, 400));
        intent.putExtra("outputY", DeviceUtils.dp2px(this, 400));
        intent.putExtra("return-data", false);
        savePath = Uri.fromFile(new File(FileUtils.getUploadPhotoFile(this)));
        intent.putExtra(MediaStore.EXTRA_OUTPUT, savePath);
        startActivityForResult(intent, code);
    }

    private void getBitmapFromResult(Intent data, ImageView iv) {

        Map<String, String> params = new HashMap<>();

        Map<String, String> textParams = new HashMap<>();
        textParams.put("bizImgPath", "show_h5");
        String result = BitmapUtil.getPathByUri4kitkat(this,
                savePath);
        params.put("iconFile", result);
//            Bitmap b = (Bitmap) data.getExtras().get("data");
        Bitmap b = BitmapFactory.decodeFile(savePath.getPath());
        showLoading();
        new Thread(() -> {
            FileUploadUtil.uploadImageFile(API.FILEUPLOAD_HOST + API.UPLOAD_FILE,
                    textParams, params, mHandler, String.valueOf(iv.getTag()));
        }).start();

        if (b != null) {
            iv.setImageBitmap(b);
        }

    }

    private int getCode(int code) {
        switch (code) {
            case CODE_CAMERA_01:
            case CODE_PHOTO_01:
                return CODE_CROP_01;
            case CODE_CAMERA_02:
            case CODE_PHOTO_02:
                return CODE_CROP_02;
            case CODE_CAMERA_03:
            case CODE_PHOTO_03:
                return CODE_CROP_03;
            case CODE_CAMERA_04:
            case CODE_PHOTO_04:
                return CODE_CROP_04;


        }
        return 0;
    }

    private void showPhotoSelectedDialog(int index) {
        View view = View.inflate(this, R.layout.layout_choosephoto_dialog, null);
        BottomPopupWindow popupWindow = new BottomPopupWindow(this, view);
        popupWindow.show(this);
        view.findViewById(R.id.tvCamera).setOnClickListener(
                (v) -> {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//                    intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
                    path = FileUtils.getUploadPhotoFile(this);
                    File file = new File(path);
                    try {
                        file.createNewFile();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
                    startActivityForResult(intent,
                            index == 1 ? CODE_CAMERA_01 :
                                    index == 2 ? CODE_CAMERA_02 :
                                            index == 3 ? CODE_CAMERA_03 : CODE_CAMERA_04);
                    popupWindow.dismiss();
                }
        );
        view.findViewById(R.id.tvPhoto).setOnClickListener(
                (v) -> {
                    Intent intent = new Intent();
                    intent.setType("image/*");
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                    startActivityForResult(intent,
                            index == 1 ? CODE_PHOTO_01 :
                                    index == 2 ? CODE_PHOTO_02 :
                                            index == 3 ? CODE_PHOTO_03 : CODE_PHOTO_04);
                    popupWindow.dismiss();
                }
        );
    }

    private void startPhotoZoom(Intent data, int code) {

        Uri uri = Uri.fromFile(new File(path));
        /**
         * 指定了保存路径之后，data返回会空
         */

        /*if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
            //这里如果是false，就是旧版本的uri
            if (DocumentsContract.isDocumentUri(this, data.getData())) {
                String path = FileUtils.getUploadPhotoFile(this);
                uri = Uri.fromFile(new File(path));
            } else {
                uri = data.getData();
            }
        } else {
            String path = FileUtils.getUploadPhotoFile(this);
            uri = Uri.fromFile(new File(path));
        }
        */

        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // crop为true是设置在开启的intent中设置显示的view可以剪裁
        intent.putExtra("crop", "true");

        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);

        // outputX,outputY 是剪裁图片的宽高
        intent.putExtra("outputX", DeviceUtils.dp2px(this, 400));
        intent.putExtra("outputY", DeviceUtils.dp2px(this, 400));
        intent.putExtra("return-data", false);
        intent.putExtra("noFaceDetection", true);
        savePath = Uri.fromFile(new File(FileUtils.getUploadPhotoFile(this)));
        intent.putExtra(MediaStore.EXTRA_OUTPUT, savePath);
        startActivityForResult(intent, code);
        // overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
    }

    @Override
    public void setPresenter(AnchorApplyContract.Presenter presenter) {
        this.presenter = presenter;
    }

    @Override
    public void showResult(BaseData data) {
        if (data.getCode() == 1) {
            showTopTips(R.string.submit_success);
            tvSubmit.setEnabled(false);
            User user = Application.getUser();
            user.getAnchor().setAudit_statu(1);
            Application.setUser(user);
            mHandler.postDelayed(() -> {
                Rxbus.getDefault().post(user);
                AppManager.getAppManager().finishActivity(this);
            }, 2000);
        } else {
            showTopTips(data.getMsg());
        }
    }


    private static class MHandler extends Handler {
        WeakReference<AnchorApplyActivity> weakReference;

        public MHandler(AnchorApplyActivity activity) {
            this.weakReference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            weakReference.get().savePath = null;
            switch (msg.what) {
                case FileUploadUtil.SUCCESS:
                    if (weakReference.get() != null) {
                        weakReference.get().hideLoading();
                        weakReference.get().handlerUploadMsg(msg);
                    }
                    break;
                case FileUploadUtil.FAILED:
                    if (weakReference.get() != null) {
                        weakReference.get().hideLoading();
                        weakReference.get().showTopTips(R.string.upload_failed);
                    }
                    break;

            }

        }
    }

    private void handlerUploadMsg(Message msg) {
        switch (msg.obj.toString()) {
            case "img0":
                image_00 = msg.getData().getString(FileUploadUtil.RESULT);
                break;
            case "img1":
                image_01 = msg.getData().getString(FileUploadUtil.RESULT);
                break;
            case "img2":
                image_02 = msg.getData().getString(FileUploadUtil.RESULT);
                break;
            case "img3":
                image_03 = msg.getData().getString(FileUploadUtil.RESULT);
                break;

        }
    }

    private void submitApply() {
        if (checkInput()) {
            Map<String, Object> params = new HashMap<>();
            params.put("anchor_country", etLocation.getText().toString());
            params.put("nick_name", etNickname.getText().toString());
            params.put("anchor_country", etLocation.getText().toString());
            params.put("low_pic", image_01);
            params.put("mid_pic", image_02);
            params.put("hig_pic", image_03);
            params.put("head_icon", image_00);
            params.put("user_code", Application.getUser().getUser_code());
            if (!TextUtils.isEmpty(inviteCode.getText().toString())) {
                params.put("invite_code", inviteCode.getText().toString());
            }
            presenter.anchorApply(params);
        }

    }

    private boolean checkInput() {
        if (TextUtils.isEmpty(image_00)) {
            showTopTips(R.string.header_wrong);
            return false;
        }
        if (TextUtils.isEmpty(image_01)) {
            showTopTips(R.string.nature_look_wrong);
            return false;
        }
        if (TextUtils.isEmpty(image_02)) {
            showTopTips(R.string.paint_look_wrong);
            return false;
        }
        if (TextUtils.isEmpty(image_03)) {
            showTopTips(R.string.art_photo_wrong);
            return false;
        }

        if (etNickname.getText().toString().length() < 4) {
            showTopTips(R.string.name_length);
            return false;
        }

        if (etNickname.getText().toString().length() < 2) {
            showTopTips(R.string.room_length);
            return false;
        }

        if (TextUtils.isEmpty(etLocation.getText().toString())) {
            showTopTips(R.string.choose_location);
            return false;
        }
        return true;
    }

    @Override
    protected void onDestroy() {
        mHandler.removeCallbacksAndMessages(null);
        super.onDestroy();
    }
}
